#include "SDLWindow.h"


int sdl_main_loop(void *window);

SDLWindow::SDLWindow()
{
    mWindowID = 0;
    mWidth    = 0;
    mHeight   = 0;
}

SDLWindow::~SDLWindow()
{

}

void SDLWindow::render()
{
    //Clear screen
    SDL_SetRenderDrawColor( mRenderer, 0x00, 0x55, 0xFF, 0xFF );
    SDL_RenderClear( mRenderer );

    //Update screen
    SDL_RenderPresent( mRenderer );
}

bool SDLWindow::init(const void *winID)
{
    int i =  SDL_GetNumRenderDrivers();
    mWindow = SDL_CreateWindowFrom(winID);
    if ( !mWindow )
    {
        printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
        return false;
    }

    /* mWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,  480, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE ); */
    /* mWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,  480, SDL_WINDOW_BORDERLESS); */
    /* if ( !mWindow ) */
    /* { */
    /*     printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() ); */
    /*     return false; */
    /* } */

    //Set texture filtering to linear
    if ( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
    {
        printf( "Warning: Linear texture filtering not enabled!" );
    }
    //Create renderer for window
    //mRenderer = SDL_CreateRenderer( mWindow, 1, SDL_RENDERER_ACCELERATED| SDL_RENDERER_PRESENTVSYNC );
    mRenderer = SDL_CreateRenderer(mWindow, 1, SDL_RENDERER_ACCELERATED);
    /* mRenderer = SDL_CreateRenderer(mWindow, 1, SDL_RENDERER_SOFTWARE); */
    if ( mRenderer == NULL )
    {
        printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
        SDL_DestroyWindow( mWindow );
        mWindow = NULL;
    }
    else
    {
        //Initialize renderer color
        SDL_SetRenderDrawColor( mRenderer, 0x00, 0xFF, 0xFF, 0xFF );

        //Grab window identifier
        mWindowID = SDL_GetWindowID( mWindow );

        //Flag as opened
    }


    SDL_CreateThread(sdl_main_loop, "test", (void *)this);

    return true;
}

int sdl_main_loop(void *window)
{
    SDLWindow *sdlWin = (SDLWindow *)window;
    int cnt = 25*10;
    while (cnt-- > 0)
    {
        sdlWin->render();
        SDL_Delay(40);
    }
}
